package org.sippr.rvt2ifc.utils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Map;

public class HttpUtil {
    public static String Get(String url, Map<String, Object> params) {
        try {
            URL apiUrl = new URL(url);
            if (params != null) {
                String para = "?";
                for (Map.Entry<String, Object> entry : params.entrySet()) {
                    String key = entry.getKey();
                    Object value = entry.getValue();
//                System.out.println("Key: " + key + ", Value: " + value);
                    para += key + "=" + value + "&";
                }
                para = para.substring(0, para.length() - 1);
                apiUrl = new URL(url + para);
            }


            HttpURLConnection connection = (HttpURLConnection) apiUrl.openConnection();
            connection.setRequestMethod("GET");
            int responseCode = connection.getResponseCode();
            if (responseCode != 200) {
                System.out.println("服务器异常," + url);
                return null;
            }
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuilder response = new StringBuilder();
            return in.readLine();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    //通过访问某服务，判断服务器是否在线
    public static Boolean IsOnLine(String url) {
        try {
            URL apiUrl = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) apiUrl.openConnection();
            connection.setRequestMethod("GET");
            int responseCode = connection.getResponseCode();
            if (responseCode != 200) {
                System.out.println("服务器异常," + url);
                return false;
            }
            return true;
        } catch (Exception e) {
//            System.out.println(e);
            return false;
        }
    }

    public static String PostByBody(String url, Map<String, Object> params) {
        try {

            // 构造请求 JSON 数据
            String jsonInputString = JsonUtil.writeValueAsString(params);

            // 创建 URL 对象
            URL obj = new URL(url);

            // 创建 HttpURLConnection 对象
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();

            // 设置请求方法为 POST
            con.setRequestMethod("POST");

            // 设置请求头信息
            con.setRequestProperty("Content-Type", "application/json");

            // 允许输出数据
            con.setDoOutput(true);

            // 获取输出流对象
            try (OutputStream os = con.getOutputStream()) {
                // 将 JSON 数据写入输出流
                byte[] input = jsonInputString.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }

            // 获取响应状态码
            int responseCode = con.getResponseCode();
            if (responseCode != 200) {
                System.out.println("服务器异常," + url);
                return null;
            }
            // 读取响应数据
            try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) {
                StringBuilder response = new StringBuilder();
                // 打印响应结果
//                System.out.println("Response Code : " + responseCode);
//                System.out.println("Response Body : " + response.toString());
                return in.readLine();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static String PostByJson(String url, Map<String, Object> params) {
        try {


            // 创建 URL 对象
            URL obj = new URL(url);

            // 创建 HttpURLConnection 对象
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();

            // 设置请求方法为 POST
            con.setRequestMethod("POST");

            // 设置请求头信息
            con.setRequestProperty("Content-Type", "application/json");
            con.setRequestProperty("Accept", "application/json");

            // 允许输出数据
            con.setDoOutput(true);
            if (params != null) {
                // 构造请求 JSON 数据
                String jsonInputString = JsonUtil.writeValueAsString(params);
                // 获取输出流对象
                try (OutputStream os = con.getOutputStream()) {
                    // 将 JSON 数据写入输出流
                    byte[] input = jsonInputString.getBytes(StandardCharsets.UTF_8);
                    os.write(input, 0, input.length);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }


            // 获取响应状态码
            int responseCode = con.getResponseCode();
            if (responseCode != 200) {
                System.out.println("服务器异常, 响应码: " + responseCode);
                System.out.println("响应消息: " + con.getResponseMessage());
                System.out.println("服务器异常," + responseCode + url);
                System.out.println(con.getResponseMessage());
                return null;
            }
            // 读取响应数据
            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            StringBuilder response = new StringBuilder();
            // 打印响应结果
            System.out.println("Response Code : " + responseCode);
            System.out.println("Response Body : " + response.toString());
            return in.readLine();

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
